<?php
namespace ShenerCloud\Data\Model;

class Source
{
    public $title;
    public $media;
    public $type;
    public $images;
    public $description;
    public $batch;
    public $share;
    public $url;
    public $expire_in;
    private $items=array();
    
    public function __construct(string $title='',string $media='',int $type=0
        ,string $images='',string $description='',string $batch='',int $share=0
        ,string $url='',int $expire_in=0)
    {
        $this->title = $title;
        $this->media = $media;
        $this->type = $type;
        $this->images = $images;
        $this->description = $description;
        $this->batch = $batch;
        $this->share = $share;
        $this->url = $url;
        $this->expire_in = $expire_in;
    }
    
    /***
     * 解析服务器请求结果数据
     * @param array $params
     * @return \ShenerCloud\Data\Model\Source
     */
    public function parseRequest(array $params)
    {
        $this->items = [];
        if (isset($params['Items']) && is_array($params['Items']) 
            && count($params['Items']) > 0)
        {//资源列表数据
            foreach ($params['Items'] as $k=>$v)
            {
                if ($item = $this->parseSourceItem($v))
                    array_push($this->items, $item);
            }
        }else{//当普通资源信息处理
            if ($item = $this->parseSourceItem($params['Items']))
                array_push($this->items, $item);
        }
        return $this;
    }
    
    /***
     * 解析单个资源数据
     * @param array $item
     * @return boolean|\ShenerCloud\Data\Model\Source
     */
    private function parseSourceItem(array $item=[])
    {
        if (!is_array($item) || count($item) <= 0)
            return false;
        $title = isset($item['Title'])?$item['Title']:'';
        $media = isset($item['Media'])?$item['Media']:'';
        $type = isset($item['Type'])?intval($item['Type']):0;
        $images = isset($item['Thumb'])?$item['Thumb']:'';
        $description = isset($item['Description'])?$item['Description']:'';
        $batch = isset($item['Batch'])?$item['Batch']:'';
        $share = isset($item['Share'])?intval($item['Share']):0;
        $url = isset($item['Link'])?$item['Link']:'';
        $expire_in = isset($item['Expire_in'])?intval($item['Expire_in']):0;
        return new self($title,$media,$type,$images,$description,$batch,$share,$url,$expire_in);
    }
    
    /***
     * 获取列表数据
     * @return array
     */
    public function getList(){
        return $this->items;
    }
    
    /***
     * 获取单条数据
     * @return \ShenerCloud\Data\Model\Source|mixed
     */
    public function getOne(){
        return isset($this->items[0])?$this->items[0]:new self();
    }
}